import React, {Component} from 'react';
import {Tools, Bubble} from 'weaver-mobile';
import has from 'lodash/has';
import isEmpty from 'lodash/isEmpty';

window.showEmAlarm = true;

const getLabel = Tools.getLabel;

const getBrowserType = () => {
    if(has(Tools.ua, 'browser'))
        return Tools.ua.browser.toLowerCase();
    return null;
}

const checkJsApi = func => {
    let msg = '';
    if(window.em){
        let flag = true;
        if(Array.isArray(func)){
            let arr = [];
            func.map(f => {
                if(!window.em.checkJsApi(f))
                    arr.push(f);
            });
            if(arr.length > 0){
                msg = `${arr.join(',')} not found`;
            }
        }else if(typeof(func) == 'string'){
            flag = window.em.checkJsApi(func);
            !flag && (msg = `${func} not found`);
        }
    }else{
        msg = 'em not found';
        Bubble.error(msg);
    }
    let flag = isEmpty(msg);
    return flag;
}

const openLink = url => {
    if(checkJsApi('openLink')) {
        window.em.openLink({
            url,
            openType: 2,
            sysId: window.localStorage.emobile_ec_id
        });
    }else{
        window.location.href = url;
    }
}

//获取设别信息
const getDeviceInfo = async () => {
    let funcName = getBrowserType() == 'dingtalk' ? 'getNetWorkInfo' : 'getClientInfo';
    return new Promise((resolve, reject) => {
        if(checkJsApi(funcName)){
            window.em.ready(() => {
                window.em[funcName]({
                    success: res => {
                        resolve({status: '1', ...res});
                    },
                    fail: res => {
                        Bubble.error(<div onClick={() => Bubble.error(JSON.stringify(res.errMsg))}>{getLabel('504566','无法获取设备信息')}</div>);
                        resolve({status: '-1'});
                    }
                })
            })
        }else{
            if(getBrowserType() == 'emobile')
                Bubble.error(`${getLabel('504566','无法获取设备信息')}`);
            resolve({status: '-1'});
        }
    })
}

//获取实时定位
const getLocation = async (mapUtil, onLocationChangedHandle) => {
    const {isAmap, isGoogleMap, googleMapKey} = mapUtil || {};
    const params = {};
    if(isAmap){
        Object.assign(params, {type: 'gcj02'});
    }else if(isGoogleMap){
        Object.assign(params, {
            locationType: 'Google',
            ios_googleMap_key: googleMapKey,
            and_googleMap_key: googleMapKey
        })
    }else{
        Bubble.error('maptype undefined');
        return {status: '-1'};
    }

    const func = ['getLocation'];
    getBrowserType() == 'dingtalk' && func.push('dingAuthFunc');

    const locationInfo = await new Promise((resolve, reject) => {
        if(checkJsApi(func)){
            func.includes('dingAuthFunc') && window.em.dingAuthFunc();
            window.em.ready(() => {
                window.em.getLocation({
                    ...params,
                    success: res => {
                        resolve({status: '1', ...res});
                    },
                    onLocationChanged: res => {
                        if(typeof(res) === 'string')
                            res = JSON.parse(res);
                        onLocationChangedHandle && onLocationChangedHandle({status: '1', ...res});
                    },
                    fail: res => {
                        Bubble.error(<div onClick={() => Bubble.error(JSON.stringify(res.errMsg))}>{getLabel('504565','无法获取定位信息')}</div>);
                        resolve({status: '-1'});
                    }
                })
            })
        }else{
            resolve({status: '0'});
        }
    });
    const {status, address} = locationInfo;
    if(status == '1'){
        if(isEmpty(address)){
            const data = await mapUtil.regeo(locationInfo);
            Object.assign(locationInfo, data);
        }
    }else if(status == '0'){
        return {status: '-1'};
        //test
        // return {
        //     address: '中国上海市闵行区联航路召楼路',
        //     longitude: 121.52646,
        //     latitude: 31.08013,
        //     status: '1'
        // }
    }
    return locationInfo;
}

//人脸识别
const checkFaceId = async securityType => new Promise((resolve, reject) => {
    if(checkJsApi(['securitySupport', 'securityEvaluation'])){
        window.em.ready(() => {
            window.em.securitySupport({
                success: res => {
                    window.em.securityEvaluation({
                        type: securityType,
                        success: res => {
                            resolve({status: '1'});
                        },
                        fail: res => {
                            Bubble.error(<div onClick={() => Bubble.error(JSON.stringify(res))}>{getLabel('511614','人脸识别失败')}</div>);
                            resolve({status: '-1'});
                        },
                        cancel: res => {
                            resolve({status: '-2'});
                        }
                    })
                },
                fail: res => {
                    Bubble.error(<div onClick={() => Bubble.error(JSON.stringify(res))}>{getLabel('511613','人脸识别服务异常')}</div>);
                    resolve({status: '-1'});
                }
            })
        })
    }else{
        if(getBrowserType() == 'emobile')
            Bubble.error(`${getLabel('511613','人脸识别服务异常')}`);
        resolve({status: '-1'});
    }
})

export {
    openLink,
    getDeviceInfo,
    getLocation,
    checkFaceId,
    getBrowserType
}